import React, { useState, useMemo, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Notebook } from '../../types/index';
import styles from './Review.module.css';
import { fetchReviewCards, submitCardReview } from './reviewApi';
import { fetchNotebooks } from '../Layout/notebookApi';
import ReviewCard, { ReviewFeedback } from './ReviewCard';
import ReviewStats from './ReviewStats';
import NotebookSelector from './NotebookSelector';
import ContinueReview from './ContinueReview';

//组合复习卡片组件、复习统计组件、继续复习组件

const ReviewView: React.FC = () => {
  const { notebookId: routeNotebookId } = useParams();
  const navigate = useNavigate();
  const [currentCardIndex, setCurrentCardIndex] = useState(0);
  const [showAnswer, setShowAnswer] = useState(false);
  const [selectedNotebookId, setSelectedNotebookId] = useState<string | undefined>(routeNotebookId);
  const [notebooks, setNotebooks] = useState<Notebook[]>([]);
  const [reviewCards, setReviewCards] = useState<Card[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  const [reviewStats, setReviewStats] = useState({
    total: 0,
    remembered: 0,
    fuzzy: 0,
    forgot: 0,
    startTime: new Date(),
  });

  // 加载笔记本数据
  useEffect(() => {
    const loadNotebooks = async () => {
      try {
        const data = await fetchNotebooks();
        console.log('获取到的笔记本数据:', data);
        setNotebooks(data);
      } catch (e) {
        console.error('获取笔记本列表失败', e);
        setError('获取笔记本列表失败');
      }
    };
    loadNotebooks();
  }, []);

  // 加载复习卡片
  useEffect(() => {
    const loadReviewCards = async () => {
      setLoading(true);
      setError(null);
      try {
        console.log('正在获取复习卡片，笔记本ID:', selectedNotebookId);
        const cards = await fetchReviewCards(selectedNotebookId);
        console.log('获取到的复习卡片:', cards);
        setReviewCards(cards);
        
        // 重置复习统计
        setReviewStats({
          total: cards.length,
          remembered: 0,
          fuzzy: 0,
          forgot: 0,
          startTime: new Date(),
        });
        
        setCurrentCardIndex(cards.length > 0 ? 0 : -1);
        setShowAnswer(false);
      } catch (e) {
        console.error('获取复习卡片失败', e);
        setError('获取复习卡片失败');
      }
      setLoading(false);
    };
    
    loadReviewCards();
  }, [selectedNotebookId]);

  // 根据有复习卡片的笔记本筛选
  const notebooksWithCards = useMemo(() => {
    if (reviewCards.length === 0) return [];
    
    const notebookIds = new Set(reviewCards.map(card => card.notebook_id));
    return notebooks.filter(notebook => notebookIds.has(notebook.id));
  }, [notebooks, reviewCards]);

  // 根据selectedNotebookId过滤卡片
  const filteredCards = useMemo(() => {
    return selectedNotebookId 
      ? reviewCards.filter(card => card.notebook_id === selectedNotebookId)
      : reviewCards;
  }, [reviewCards, selectedNotebookId]);

  const handleFeedback = async (feedback: ReviewFeedback) => {
    if (currentCardIndex < 0 || currentCardIndex >= filteredCards.length) return;
    
    const currentCard = filteredCards[currentCardIndex];
    
    // 更新复习统计
    setReviewStats(prev => ({
      ...prev,
      [feedback === ReviewFeedback.REMEMBERED ? 'remembered' :
       feedback === ReviewFeedback.FUZZY ? 'fuzzy' : 'forgot']: prev[feedback === ReviewFeedback.REMEMBERED ? 'remembered' :
       feedback === ReviewFeedback.FUZZY ? 'fuzzy' : 'forgot'] + 1
    }));
    
    // 提交卡片复习结果
    try {
      await submitCardReview(currentCard.id, feedback);
    } catch (e) {
      console.error('提交复习结果失败', e);
      setError('提交复习结果失败');
    }
    
    // 处理下一张卡片
    handleNextCard();
  };

  const handleNextCard = () => {
    if (currentCardIndex < filteredCards.length - 1) {
      setCurrentCardIndex(currentCardIndex + 1);
      setShowAnswer(false);
      return;
    }

    // 如果没有下一张卡片，检查当前是"复习所有笔记本"模式还是"复习单个笔记本"模式
    if (!selectedNotebookId) {
      // "复习所有笔记本"模式，直接统计复习数据
      setCurrentCardIndex(-1);
      setShowAnswer(false);
    } else {
      // "复习单个笔记本"模式，尝试切换到下一个笔记本继续复习
      const otherNotebooksWithCards = notebooksWithCards.filter(nb => 
        nb.id !== selectedNotebookId
      );

      if (otherNotebooksWithCards.length > 0) {
        setCurrentCardIndex(-2);
        setShowAnswer(false);
      } else {
        setCurrentCardIndex(-1);
        setShowAnswer(false);
      }
    }
  };

  const setSelectedNotebook = (notebookId: string | undefined) => {
    setSelectedNotebookId(notebookId);
  };

  const handleNotebookChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newNotebookId = e.target.value === "all" ? undefined : e.target.value;
    setSelectedNotebook(newNotebookId);
  };

  const handleSelectNotebook = (notebookId: string) => {
    setSelectedNotebook(notebookId);
  };

  const getNotebookName = (notebookId: string) => {
    const notebook = notebooks.find(nb => nb.id === notebookId);
    return notebook ? notebook.name : "未知笔记本";
  };

  // 渲染不同的复习状态
  const renderReviewState = () => {
    // 移除调试信息显示
    if (loading) {
      return (
        <div className={styles.reviewHeader}>
          <h2>加载中...</h2>
        </div>
      );
    }

    if (error) {
      return (
        <div className={styles.reviewHeader}>
          <h2>出错了: {error}</h2>
        </div>
      );
    }

    if (notebooksWithCards.length === 0 || filteredCards.length === 0) {
      return (
        <div className={styles.reviewHeader}>
          <h2>暂无可复习的卡片</h2>
        </div>
      );
    }

    if (currentCardIndex === -1) {
      const endTime = new Date();
      const duration = Math.round((endTime.getTime() - reviewStats.startTime.getTime()) / 1000 / 60);

      return (
        <div className={styles.reviewHeader}>
          <h2>所有笔记本复习完成！</h2>
          <ReviewStats stats={reviewStats} duration={duration} />
        </div>
      );
    }

    if (currentCardIndex === -2) {
      const otherNotebooksWithCards = notebooksWithCards.filter(nb => 
        nb.id !== selectedNotebookId
      );

      return (
        <div className={styles.reviewHeader}>
          <h2>当前笔记本复习完成！</h2>
          <ReviewStats stats={reviewStats} />
          <ContinueReview
            otherNotebooks={otherNotebooksWithCards}
            onSelectNotebook={handleSelectNotebook}
          />
        </div>
      );
    }

    const currentCard = filteredCards[currentCardIndex];
    const progress = filteredCards.length > 0 
      ? ((currentCardIndex + 1) / filteredCards.length) * 100
      : 0;

    return (
      <>
        <div className={styles.reviewHeader}>
          <h2>今日复习 <span className={styles.reviewCount}>{currentCardIndex + 1}/{filteredCards.length}</span></h2>
          <NotebookSelector
            selectedNotebookId={selectedNotebookId}
            notebooksWithCards={notebooksWithCards}
            onChange={handleNotebookChange}
          />
          <div className={styles.reviewProgress}>
            <div className={styles.progressBar} style={{ width: `${progress}%` }}></div>
          </div>
        </div>

        <ReviewCard
          card={currentCard}
          showAnswer={showAnswer}
          onShowAnswer={() => setShowAnswer(true)}
          onFeedback={handleFeedback}
          getNotebookName={getNotebookName}
        />
      </>
    );
  };

  return (
    <div className={styles.reviewView}>
      {renderReviewState()}
    </div>
  );
};

export default ReviewView; 